
class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
        next = null;
    }
}

/**
 *160. 相交链表
 * https://leetcode.cn/problems/intersection-of-two-linked-lists/description/
 */
public class Solution3 {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode curA = headA, curB = headB;
        int countA = 0, countB = 0;
        while (curA != null){
            countA++;
            curA = curA.next;
        }
        while (curB != null) {
            countA++;
            curB = curB.next;
        }
        int x = Math.abs(countA - countA);
        curA = headA;
        curB = headB;
        if (countA > countB) {
            while (countA-- > 0) {
                curA = curA.next;
            }
        } else if (countA < countB) {
            while (countB-- > 0) {
                curB = curB.next;
            }
        }

        while (curA != null) {
            if (curA.val == curB.val) {
                return curA;
            }
            curA = curA.next;
            curB = curB.next;
        }

        return new ListNode(0);
    }
}